package com.rxyb.security.config;

import com.rxyb.security.common.BusiUserAuthenticationConverter;
import com.rxyb.security.exception.BusiAccessDeniedHandler;
import com.rxyb.security.exception.BusiAuthExceptionEntryPoint;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.web.client.RestTemplate;

/**
 * @author YJH
 * @version 1.0
 * @description 使用restTemplate负载均衡
 * token获取用户信息转成用户的详细信息
 * 动态设置不拦截的url：security.oauth2.client.ignore-url-list
 * @date 2020/5/27  14:28
 */
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {


    @Autowired
    private  RemoteTokenServices remoteTokenServices;

    @Autowired
    private  RestTemplate lbRestTemplate;

    @Autowired
    private  IgnoreUrlProperties ignoreUrlProperties;




    @Override
    @SneakyThrows
    public void configure(HttpSecurity httpSecurity) throws Exception {
        //允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        httpSecurity.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>
                .ExpressionInterceptUrlRegistry registry = httpSecurity
                .authorizeRequests();
        ignoreUrlProperties.getIgnoreUrlList().forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated().
                and().csrf().disable();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        System.out.println("访问i资源");
        resources.resourceId("authorize-server"); //重点，设置资源id
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        // token 管理
        UserAuthenticationConverter userTokenConverter = new BusiUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userTokenConverter);

        // 负载均衡
        remoteTokenServices.setRestTemplate(lbRestTemplate);
        // token 管理
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);
        resources.tokenServices(remoteTokenServices);

        resources.authenticationEntryPoint(new BusiAuthExceptionEntryPoint()).accessDeniedHandler(new BusiAccessDeniedHandler());
    }
}
